<template>
  <div>
    <!-- 合同附件 -->
    <el-dialog title="合同附件" :visible.sync="visible" :close-on-click-modal="false" style="margin-top: 100px" width="1024px" top="5vh" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleDownload"
            :disabled="this.checkFileList.length == 0"
          >下载</el-button>
        </el-col>
      </el-row>

      <div class="img-list">
        <div class="img-li-box" v-for="(item,key) in fileList" :key="key" :title="getTitle(item)">
          <img class="img-li-b--url" :src="getFileSuffix(item)">
          <div class="img-li-b--bottom">
            <div class="img-li-b--name">{{ item.fileName }}</div>
          </div>

          <div class="img-li-b--check">
            <el-checkbox v-model="item.checked" :disabled="item.disabled" :key="item.fileId" v-hasPermi="['project:project:download']"
                         @change="checked=>handleCheckFile(checked, item.fileId, item)"></el-checkbox>
          </div>

          <!-- 删除icon -->
          <div class="img-li-b--delete">
            <i @click="handleFileRemove(item.fileName, item.fileId)" class="el-icon-delete"></i>
          </div>

          <!-- 放大icon -->
          <div class="img-li-b--layer" v-if="item.isImg == 'Y'" @click="handleFileEnlarge(item.fileId, item.filePath)" >
            <i class="el-icon-view"></i>
          </div>

          <!-- 下载 -->
          <div class="img-li-b--layer" v-if="item.isImg == 'N'" @click="handleFileDownload(item.fileId)">
            <i class="el-icon-download"></i>
          </div>
        </div>

        <!-- 上传进度 -->
        <div v-if="!pass && progress !== 0" class="img-li-box img-li-b--progress">
          <el-progress type="circle" :percentage="progress" :width="80" :status="proStatus"></el-progress>
        </div>

        <!-- 上传按钮 -->
        <div class="img-li-b--upload">
          <el-upload
            class="img-li-b--upl--field"
            accept=".doc,.docx,.pdf,.ppt,.pptx,.txt,.xls,.xlsx,.jpg,.png,.jpeg,.zip,.rar"
            ref="upload"
            list-type="picture-card"
            multiple
            :show-file-list="false"
            :action="uploadFileUrl"
            :headers="headers"
            :data="{uuid: uuid}"
            :on-change="handleOnChange"
            :before-upload="handleBeforeUpload"
            :on-success="handleOnSuccess"
            :on-error="handleOnError"
            :on-progress="handleOnProgress">
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>

      </div>

    </el-dialog>

    <!-- 放大弹窗 -->
    <el-dialog title="图片预览"
               :visible.sync="isEnlargeImage"
               :modal-append-to-body="false"
               width="60%">

      <el-row>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleImageFileDownload">下载图片</el-button>
      </el-row>
      <img @click="isEnlargeImage = false" style="width:100%; height: 100%;padding-top: 10px;" :src="enlargeImage">

    </el-dialog>

  </div>
</template>
<script>
  import { getStaffContractFileList, delStaffContractFile } from "@/api/site/labour/contract";
  import { getToken } from "@/utils/auth";
  import doc from "@/assets/file/doc.png";
  import xls from "@/assets/file/xls.png";
  import txt from "@/assets/file/txt.png";
  import pdf from "@/assets/file/pdf.png";
  import ppt from '@/assets/file/ppt.png';
  import zip from '@/assets/file/zip.png';
  import { Loading, Message } from 'element-ui';
  import axios from 'axios';
  import { blobValidate } from '@/utils/master';
  import errorCode from '@/utils/errorCode';

  export default {
    name: 'StaffContractFile',
    props: {
      // 文件数量限制
      limit: {
        type: Number,
        default: 5,
      },
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 5,
      }
    },
    data() {
      return {
        // uuid
        uuid: null,
        // 上一次操作之前的数量
        lastFileCount: 0,
        // 附件数量
        fileCount: 0,
        // 上传按钮是否显示
        uploadShow: true,
        // 遮罩层
        visible: false,
        // 文件ID
        fileId: null,
        baseUrl: process.env.VUE_APP_BASE_API,
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/labour/staff/contract/file/upload",
        headers: {
          token: "Bearer " + getToken(),
        },
        // 文件集合
        fileList: [],
        doc: doc,
        pdf: pdf,
        ppt: ppt,
        txt: txt,
        xls: xls,
        zip: zip,
        //上传进度
        progress: 0,
        //是否上传成功
        pass: null,
        //放大图片
        isEnlargeImage: false,
        //放大图片地址
        enlargeImage: '',
        // 选中列表
        checkFileList: [],
        // 禁用
        disabled: false
      }
    },
    computed: {
      proStatus() {
        //上传状态
        if (this.pass) {
          return 'success'
        } else if (this.pass === false) {
          return 'exception'
        } else {
          return 'warning'
        }
      }
    },
    // 方法
    methods: {
      // 显示弹框
      show(uuid) {
        this.fileList = [];
        this.uuid = uuid;
        this.getFileList(0);
        // 延迟显示，先数据刷新出来
        setTimeout(() =>{
          this.visible = true;
        },300);
      },
      // 获取附件列表
      getFileList(flag) {
        getStaffContractFileList({uuid: this.uuid}).then(response => {
          this.fileList = response.list;
          this.fileCount = response.fileCount;
          if (flag == 0) {
            this.lastFileCount = response.fileCount;
          }
          console.log(flag);
          // flag 为0，是初始化刷新，不需要刷新父项数据
          // flag 为1，是新增后刷新，如果数量为1，则是由0变1的过程，需要刷新父项数据
          // flag 为2，是删除后刷新，如果数量为0，则是有1变0的过程，需要刷新父项数据
          if (flag != 0) {
            if (flag == 1) {
              if (this.lastFileCount == 0 && this.fileCount > 0) {
                this.lastFileCount = response.fileCount;
                this.$parent.getStaffContractList();
              }
            } else {
              this.lastFileCount = response.fileCount;
              if (this.fileCount == 0) {
                this.$parent.getStaffContractList();
              }
            }
          }
        });
      },
      // 获取文件后缀
      getFileSuffix(file) {
        let suffix = file.fileName.substring(file.fileName.lastIndexOf(".") + 1).toLowerCase();
        if (file.isImg == 'Y') {
          return process.env.VUE_APP_BASE_API + file.filePath;
        } else {
          if (suffix == "doc" || suffix == "docx") {
            return this.doc;
          } else if (suffix == "pdf") {
            return this.pdf;
          }  else if (suffix == "ppt" || suffix == "pptx") {
            return this.ppt;
          } else if (suffix == "txt") {
            return this.txt;
          } else if (suffix == "xls" || suffix == "xlsx") {
            return this.xls;
          } else if (suffix == "zip" || suffix == "rar") {
            return this.zip;
          }
        }
      },
      // 上传前loading加载
      handleBeforeUpload(file) {
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
      },
      // 文件个数超出
      handleExceed() {
        this.$modal.msgError(`一次批量上传文件数量不能超过 ${this.limit} 个!`);
      },
      // 上传进度
      handleOnProgress(e, file) { //开始上传
        this.progress = Math.floor(e.percent)
      },
      // 发生变化
      handleOnChange(file) {
        if (file.status == 'ready') {
          this.pass = null;
          this.progress = 0;
        } else if (file.status == 'fail') {
          this.$message.error("文件上传出错，请刷新重试！")
        }
      },
      // 上传成功
      handleOnSuccess(e, file) {
        this.pass = true;
        this.$message.success("上传成功");
        this.getFileList(1);
      },
      // 上传失败
      handleOnError(e, file) {
        this.pass = false;
      },
      // 删除文件
      handleFileRemove(fileName, fileId) {
        this.$modal.confirm('确认删除文件[' + fileName + ']？').then(function() {
          return delStaffContractFile(fileId);
        }).then(() => {
          this.getFileList(2);
          this.$message.success("删除成功");
        }).catch(() => {});
      },
      // 下载文件
      handleFileDownload(fileId) {
        this.$download.staffContractFile(fileId);
      },
      // 放大图片
      handleFileEnlarge(fileId, _url) {
        this.fileId = fileId;
        if (_url) {
          this.enlargeImage = process.env.VUE_APP_BASE_API + _url;
          this.isEnlargeImage = !this.isEnlargeImage;
        }
      },
      // 预览图片对话框下载文件
      handleImageFileDownload() {
        this.$download.staffContractFile(this.fileId);
      },
      getTitle(file) {
        let title = "名称：" + file.fileName + "\n"
          + "日期：" + file.createTime;
        return title;
      },
      // 文件checkbox change事件
      handleCheckFile(checked, fileId, item) {
        // 选中
        if (checked) {
          this.checkFileList.push(fileId);
          if (this.checkFileList.length >= 5 ) {
            this.fileList.forEach(item => {
              if (item.checked) {
                item.disabled = false;
              } else {
                item.disabled = true;
              }
            });
          }
        } else {
          // 取消,从选中数组中删除，还原所有文件的禁用状态
          for (let i=0; i < this.checkFileList.length; i++){
            if (this.checkFileList[i] == fileId){
              this.checkFileList.splice(i, 1)
              break;
            }
          }
          this.fileList.forEach(item => {
            item.disabled = false;
          });
        }
      },
      // 文件下载
      async handleDownload() {
        let downloadLoading = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", });
        const baseURL = process.env.VUE_APP_BASE_API;
        for (let i = 0; i < this.checkFileList.length; i++){
          var url = baseURL + "/labour/staff/contract/file/download?fileId=" + this.checkFileList[i];
          await axios({
            method: 'post',
            url: url,
            responseType: 'blob',
            headers: { 'token': 'Bearer ' + getToken() }
          }).then(async (res) => {
            const isLogin = await blobValidate(res.data);
            if (isLogin) {
              const blob = new Blob([res.data])
              this.saveAs(blob, decodeURI(res.headers['download-filename']))
            } else {
              this.printErrMsg(res.data);
            }
          });
        }
        downloadLoading.close();
        this.checkFileList = [];
        this.fileList.forEach(item => {
          item.disabled = false;
          item.checked = false;
        });
      },
      saveAs(text, name, opts) {
        saveAs(text, name, opts);
      },
      async printErrMsg(data) {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        Message.error(errMsg);
      }
    }
  }
</script>
<style lang="scss" scoped>

  ::v-deep .el-upload--picture-card{
    width: 100px;
    height: 100px;
  }
  ::v-deep .el-upload{
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  .img-list {
    overflow: hidden;
    width: 100%;
    height: 600px;
    overflow-y: auto;

    // 文件列表
    .img-li-box {
      float: left;
      text-align: left;
      position: relative;
      display: inline-block;
      width: 170px;
      height: 230px;
      padding: 5px;
      margin: 5px 20px 20px 0;
      border: 1px solid #d1dbe5;
      border-radius: 4px;
      transition: all .3s;
      box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .12), 0 0 6px 0 rgba(0, 0, 0, .04);

      // 图片
      .img-li-b--url {
        display: block;
        width: 100%;
        height: 140px;
        margin: 0 auto;
        border-radius: 4px;
      }

      // 底部
      .img-li-b--bottom {
        margin-top: 10px;
        // 名称
        .img-li-b--name {
          width: 90%;
          text-overflow: ellipsis;
          overflow: hidden;
          height: 50px;
          line-height: 25px;
        }
      }

      // 选择checkbox
      .img-li-b--check {
        position: absolute;
        bottom: 10px;
        left: 10px;
        color: #8492a6;
        cursor: pointer;
        font-size: 1.1em;
      }

      // 删除按钮
      .img-li-b--delete {
        position: absolute;
        bottom: 10px;
        right: 10px;
        color: #8492a6;
        cursor: pointer;
        font-size: 1.1em;
      }

      // 放大遮罩层
      .img-li-b--layer {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        /*height: 200px;*/
        height: 145px;
        color: #fff;
        text-align: center;
        z-index: 5;
        background-color: rgba(0, 0, 0, .4);

        // 放大按钮
        i {
          font-size: 1.6em;
          /*margin-top: 80px;*/
          margin-top: 55px;
        }
      }

      .img-li-b--delete,
      .img-li-b--layer {
        opacity: 0;
        transition: all .3s;
      }

      // 悬浮可见删除 or 放大按钮
      &:hover {
        .img-li-b--delete,
        .img-li-b--layer {
          opacity: 1;
        }
      }

      // 上传进度
      &.img-li-b--progress {
        text-align: center;
        padding-top: 20px;
      }

    }
    // 上传按钮
    .img-li-b--upload {
      float: left;
      width: 170px;
      height: 230px;
      display: table;
      text-align: center;

      .img-li-b--upl--field {
        width: 100%;
        display: table-cell;
        vertical-align: middle;
      }
    }
  }
</style>
